package com.qianyucc.guishi.advice;

import com.qianyucc.guishi.global.*;
import com.qianyucc.guishi.model.vo.*;
import lombok.extern.slf4j.*;
import org.springframework.validation.*;
import org.springframework.web.bind.*;
import org.springframework.web.bind.annotation.*;

/**
 * @author lijing
 * @date 2019-10-12 10:37
 * @description 全局异常处理
 */
@Slf4j
@ControllerAdvice
class ExceptionHandlerAdvice {
    @ResponseBody
    @ExceptionHandler(value = GuiShiException.class)
    public RespDataVO handleGuiShiException(GuiShiException e) {
        log.error("guishi handleGuiShiException : {}", e.getMessage());
        return RespDataVO.create(e);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public RespDataVO handleException(Exception e) {
        log.error(e.getMessage());
        return RespDataVO.error("出现错误");
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RespDataVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        return RespDataVO.error(getMessage(e));
    }

    /**
     * 结合BeanValid，格式化异常信息
     *
     * @param e
     * @return
     */
    private String getMessage(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();
            Object value = error.getRejectedValue();
            String msg = error.getDefaultMessage();
            String message = String.format("错误字段：%s，错误值：%s，原因：%s；", field, value, msg);
            sb.append(message);
        }
        return sb.toString();
    }

}
